<?php

namespace app\admin\model;

use fast\Http;
use think\Config;
use think\Db;
use think\Log;
use think\Model;


class Comment extends Model
{


    // 表名
    protected $name = 'goods_comment';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
//        'ctime_text'
    ];

    /**
     * @Explain :拉取天猫商品评论数据
     * @param $id
     * @return bool|int|string
     * @Date : 2020/8/29 17:41
     * @Author : 河南邦耀网络科技有限公司
     */
    public function pullTmallGoodsComment($id){
        set_time_limit(0);
        $config=Config::get("data_conf");
        $totalPage=mt_rand(5,20);
        $page=1;
        $res=false;
        echo date('Ymd H:i').'-开始写入商品['.$id."] \n";
        do{
            $url=$config['TmallItemComment'].'?apikey='.$config['TmallApiKey'].'&page='.$page.'&sort=1&itemId='.$id;
            $comment= Http::get($url);
            if(!empty($comment)) {
                $comment = json_decode($comment, true);
                $data=[
                    'itemId'=>$id,
                    'comment'=>json_encode($comment['data'],JSON_UNESCAPED_UNICODE),
                    'page'=>$page,
                    'ctime'  =>time(),
                ];
                if (empty(Db::table('pt_tmall_comment')->where(['itemId' => $id,'page'=>$page])->find()))
                    $res=Db::table('pt_tmall_comment')->insert($data);

            }else{
                Log::log('请求评论失败');
                $comment=[];
                $comment['hasNext']=false;
                continue;
            }
            $page++;
        }while($comment['hasNext'] && $page<=$totalPage);
        echo date('Ymd H:i').'-成功写入商品 ['.$id."] \n";
        return $res;
    }


    public function getCtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['ctime']) ? $data['ctime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function  getTmallCommentModel(){
        return Db::table('pt_tmall_comment');
    }


}
